#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<cstdlib>
#include<linux/input.h>


#include <unistd.h>
#include <fcntl.h>

namespace wang{
using _fd_t =int;
struct fd{
	_fd_t raw;
	fd(){raw=0;}
	fd(const char* file,int oflag){raw=open(file,oflag);}
	~fd(){close(raw);}
	auto read(void* buf,size_t nbytes){return ::read(raw,buf,nbytes);}
	auto write(const void* buf,size_t nbytes){return ::write(raw,buf,nbytes);}
	template<typename T>
	auto fill(T& container){return ::read(raw,&container,sizeof(T));}
	operator _fd_t(){return raw;}
};

} // namespace wang


using namespace std;
const char* KEYBOARD_DEV = "/dev/input/event3";
vector<string> LINES;

int main() {
	string temp_string;
	char linebuf[128];
	input_event ev;
	auto keyboard_fd = wang::fd(KEYBOARD_DEV, O_RDONLY);
	if (keyboard_fd < 0) {
		printf("open keyboard failed, error:%d\n", errno);
		return -1;
	}

	while (cin.getline(linebuf, 128)) {
		LINES.push_back(linebuf);
	}
	cout<<"--- begin with enter ,exit with 'q' ---"<<endl;
	auto it = LINES.begin();
	bool to_end=false;
	while (true) {
		auto ret = keyboard_fd.fill(ev);
		if (ret != sizeof(input_event)) { break; }

		if (ev.type != EV_KEY) { continue; }/* 消息类型，EV_KEY是按键 */
		if(ev.code==KEY_Q){break;}
		if (!to_end && ev.code == KEY_ENTER && ev.value == 1) {
			/* 按键信息，/usr/include/linux/input-event-codes.h文件中有定义键值，例如KEY_ESC对应esc按键 */
			/* 按键是按下还是释放，0释放、1按下、2长按 */
			cout <<*it <<flush;
			if (it == LINES.end()) { 
				cout<<"--------END press q to quit-------"<<endl;
				to_end = true;
			}
			else{
				++it;
			}
		}
	}
	close(keyboard_fd);
	return 0;
}

